#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include "process.h"

#define SECONDS_NUMBER 60

int main()
{
    int fd1[2],fd2[2],cld_pid;
    char buf[200], len;

    if (pipe(fd1) == -1) // 创建管道1
    {
        printf("creat pipe1 error\n");
        exit(1);
    }
    if (pipe(fd2) == -1) // 创建管道2
    {
        printf("creat pipe2 error\n");
        exit(1);
    }

    if ((cld_pid=fork()) == 0) //子进程
    {
        close(fd1[1]); // 子进程关闭管道1的写入端
        close(fd2[0]); // 子进程关闭管道1的读出端

        struct timeval time;

        GetCurrentSecond(&time);

        struct timeval nextTime;

        nextTime.tv_sec = time.tv_sec;

        nextTime.tv_usec = time.tv_usec;

        while (SECONDS_NUMBER > (nextTime.tv_sec - time.tv_sec)) {
            //子进程读管道1
            len = read(fd1[0],buf,sizeof(buf));

            if (0 >= len) {
                continue;
            }

            GetCurrentSecond(&nextTime);

            printf("\n这是在子进程，系统时间：%s\n", buf);

             memset(buf, '\0', sizeof(char)* 200);

            sprintf(buf, "当前秒数: %ld", nextTime.tv_sec - time.tv_sec);

            // 子进程写管道2
            // strcpy(buf,"子进程写入管道2的字符串");
            write(fd2[1],buf,strlen(buf));
        }

        if( nextTime.tv_sec - time.tv_sec >= SECONDS_NUMBER) {

             memset(buf, '\0', sizeof(char)* 200);

             memcpy(buf, "quit", sizeof(char)* 4);

             printf("这是在子进程：退出标志：%s\n", buf);

             write(fd2[1],buf,strlen(buf));
        }

        exit(0);
    }
    else //父进程
    {
        close(fd1[0]); // 父进程关闭管道1的读出端
        close(fd2[1]); // 父进程关闭管道2的写入端

        while (1) {

            GetNowTime(buf);
            //父进程写管道1
            // strcpy(buf,"父进程写入管道1的字符串");
            write(fd1[1],buf, strlen(buf));

            // 清理内存
            memset(buf, '\0', sizeof(char)* 200);
            //父进程读管道2
            len = read(fd2[0],buf,sizeof(buf));
            printf("这是在父进程, %s\n", buf);

            if (NULL != strstr(buf, "quit")) {
                printf("子进程已退出,父进程也要退出\n");
                break;
            }
        }

        exit(0);
    }
}
